<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2023 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\service;

use app\common\enum\UserEnum;
use app\common\model\User;
use app\common\service\FileService;
use think\Exception;

/**
 * 用户服务类
 */
class UserService
{
    protected int $terminal = UserEnum::WECHAT_MMP;

    protected User $user;

    protected array $response = [];

    public function __construct(array $response, int $terminal)
    {
        $this->terminal = $terminal;
        $this->response = $response;
    }


    /**
     * @notes 生成用户ID
     */
    public static function createUserSn($length = 10)
    {
        $rand_str = '';

        for ($i = 0; $i < $length; $i++) {
            $rand_str .= mt_rand(0, 9);
        }

        if (User::where(['sn' => $rand_str])->find()) {
            return self::createUserSn($length);
        }

        return $rand_str;
    }

    /**
     * @notes 根据opendid获取用户信息
     */
    public function getResopnseByUserInfo(): self
    {
        $openid = $this->response["openid"];
        $unionid = null;

        if (isset($this->response["unionid"])) {
            $unionid = $this->response["unionid"];
        }

        $user = User::alias('u')
            ->field('u.id,u.sn,u.mobile,u.nickname,u.avatar,u.mobile,u.is_disable,u.exp,u.integral,u.birthday,u.tag_str,u.intro,u.post_num,u.sex')
            ->where(function ($query) use ($openid, $unionid) {
                $query->whereOr(['u.openid' => $openid]);
                if (isset($unionid) && $unionid) {
                    $query->whereOr(['u.unionid' => $unionid]);
                }
            })
            ->findOrEmpty();

        $this->user = $user;
        return $this;
    }

    /**
     * @notes 获取用户信息并设置登录token
     */
    public function getUserInfo(): array
    {
        if (!$this->user->isEmpty()) {
            $this->checkAccount();
            $this->getToken();
        }

        return $this->user->toArray();

    }

    /**
     * @notes 用户授权登录，
     * 如果用户不存在，创建用户；用户存在，更新用户信息
     */
    public function authUserLogin(): self
    {
        if ($this->user->isEmpty()) {
            $this->createUser();
        }

        return $this;
    }

    /**
     * @notes 创建用户
     */
    private function createUser(): void
    {
        // 默认头像
        $avatar = config('project.default_image.user_avatar');

        $response = $this->response;

        $userSn = self::createUserSn();
        $this->user->sn = $userSn;
        $this->user->nickname = "用户" . $userSn;
        $this->user->avatar = $avatar;
        $this->user->terminal = $this->terminal;
        $this->user->openid = $response["openid"];

        if (isset($response["unionid"])) {
            $this->user->unionid = $response["unionid"];
        }

        $this->user->save();

        $this->getResopnseByUserInfo();
    }

    /**
     * @notes 校验账号是否可用
     */
    public function checkAccount()
    {
        if ($this->user->is_disable) {
            throw new Exception('您的账号异常，请联系客服。');
        }
    }

    /**
     * @notes 获取token
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author cjhao
     * @date 2021/8/2 16:45
     */
    private function getToken(): void
    {
        $user = UserTokenService::setToken($this->user->id, $this->terminal);
        $this->user->token = $user['token'];
    }

    /**
     * 计算用户等级
     * @param $exp
     * @return string
     */
    public static function userLevel($exp): string
    {

        $level = 'Lv.1';

        // Lv.1
        if ($exp < 1000) {
            $level = 'Lv.1';
        }

        // Lv.2
        if ($exp >= 1000 && $exp < 3000) {
            $level = 'Lv.2';
        }

        // Lv.3
        if ($exp >= 3000 && $exp < 5000) {
            $level = 'Lv.3';
        }

        // Lv.4
        if ($exp >= 5000 && $exp < 7000) {
            $level = 'Lv.4';
        }

        // Lv.5
        if ($exp >= 7000 && $exp < 9000) {
            $level = 'Lv.5';
        }

        // Lv.6
        if ($exp >= 9000 && $exp < 12000) {
            $level = 'Lv.6';
        }

        // Lv.7
        if ($exp >= 12000 && $exp < 16000) {
            $level = 'Lv.7';
        }

        // Lv.8
        if ($exp >= 16000 && $exp < 50000) {
            $level = 'Lv.8';
        }

        // Lv.9
        if ($exp >= 50000 && $exp < 100000) {
            $level = 'Lv.9';
        }

        // Lv.10
        if ($exp >= 100000) {
            $level = 'Lv.10';
        }

        return $level;
    }
}